package com.briup.web.controller;

import com.alipay.api.AlipayApiException;
import com.briup.bean.AlipayBean;
import com.briup.bean.Order;
import com.briup.bean.OrderItem;
import com.briup.service.IOrderService;
import com.briup.utils.Alipay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class PayController {
    @Autowired
    private Alipay alipay;
    @Autowired
    private IOrderService orderService;
    @GetMapping("/Alipay")
    @ResponseBody
    public String Alipay(String subject, String orderId, BigDecimal sumPrice) throws AlipayApiException {
        //System.out.println(orderId);
        //准备支付宝支付页面
        AlipayBean alipayBean = new AlipayBean();
        //总金额
        alipayBean.setTotal_amount(String.valueOf(sumPrice));
        //商户订单号，商户网站订单系统中唯一订单号，必填
        alipayBean.setOut_trade_no(orderId);
        //订单名称名称，必填
        alipayBean.setSubject(subject);
        //执行支付操作
        String page = alipay.pay(alipayBean);
        return page;
    }

    @GetMapping("/toPayOrder")
    public String toPayOrder( String orderId) throws Exception {
        //查询到订单
        Order order = orderService.findById(orderId);
       // System.out.println("---order" + order.getId());
       // System.out.println(order.getStatus());
        if (order != null && order.getStatus() == 1) {
            //如果存在该订单并且是未支付状态
            List<OrderItem> orderItemList = order.getOrderItems();
            //生成支付订单名称
            final String[] subject = {"【杰普官方旗舰店】"};
            orderItemList.forEach(shop -> {
                subject[0] = subject[0] + " " + shop.getShop().getName() + "×" + shop.getNum();
            });
            return "forward:/Alipay?subject="+subject[0]+"&sumPrice="+order.getSumPrice();
        } else {
            throw new Exception();
        }
    }
}
